<template>
  <SearchForm :query="query" @search="onSearch" @reset="handleReset" />

  <n-space class="py-[10px]" justify="end">
    <n-button
      ghost
      type="error"
      size="small"
      v-hasPermi="['system:role:remove']"
      :disabled="checkedRows.length === 0"
      @click="handleDeleteRoles"
    >
      <template #icon>
        <n-icon size="18"><DeleteOutlineOutlined /></n-icon>
      </template>
      删除
    </n-button>
    <n-button
      ghost
      type="success"
      size="small"
      :loading="downloadLoading"
      v-hasPermi="['system:role:export']"
      @click="handleExport"
    >
      <template #icon>
        <n-icon size="18"><FileUploadOutlined /></n-icon>
      </template>
      导出
    </n-button>
    <n-button
      ghost
      type="primary"
      size="small"
      v-hasPermi="['system:role:add']"
      @click="openDialog"
    >
      <template #icon>
        <n-icon size="18"><PlusRound /></n-icon>
      </template>
      新增
    </n-button>
  </n-space>

  <n-data-table
    ref="tableRef"
    :loading="loading"
    :columns="columns"
    :data="tableData"
    :row-key="(row: any) => row.roleId"
    :pagination="{
      page: query.page,
      pageSize: query.pageSize,
      itemCount: total,
      showSizePicker: true,
      onUpdatePage: handlePageChange,
      onUpdatePageSize: handlePageSizeChange,
    }"
    @update:checked-row-keys="handleChcekedRowKeys"
  />

  <!-- 新增、修改用户弹窗 -->
  <UpdateRoleDialog :visible="visible" :data="data" @close="handleCloseDialog"></UpdateRoleDialog>
</template>

<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import SearchForm from './components/SearchForm.vue';
import { useTable } from '@/hooks/useTable';
import { NButton, NSpace, useMessage, useDialog as useConfirmDialog } from 'naive-ui';
import { DeleteOutlineOutlined, FileUploadOutlined, PlusRound } from '@vicons/material';
import UpdateRoleDialog from './components/UpdateRoleDialog.vue';
import { useDialog } from '@/hooks/useDialog';
import { useRouter } from 'vue-router';
import { useDownload } from '@/hooks/useDownload';
import { getColumns } from './columns';
import { changeRoleStatus, deleteRole, getRoleList } from '@/apis/system/role';

defineOptions({
  name: 'Role',
});

const IconComp = ref<any>(null);

/**
 * 自动动态加载图标组件：
 * icon = "F7TimerFill"
 * pack = "ionicons5" → 实际路径：@vicons/ionicons5
 */
onMounted(async () => {
  try {
    const mod = await import(`@vicons/material`);
    IconComp.value = mod['AcUnitFilled'];
  } catch (err) {
    console.error(`图标加载失败:`, err);
  }
});

const message = useMessage();
const router = useRouter();
const checkedRows = ref<any[]>([]);
const dialog = useConfirmDialog();
const { download, loading: downloadLoading } = useDownload();
const {
  query,
  tableData,
  total,
  loading,
  handleSearch,
  handleReset,
  handlePageChange,
  handlePageSizeChange,
} = useTable({
  api: getRoleList,
  defaultQuery: {
    roleName: null,
    roleKey: null,
    status: null,
    'params[beginTime]': null,
    'params[endTime]': null,
  },
});

const { visible, data, openDialog, closeDialog } = useDialog();

// 查询表单提交
const onSearch = (values: any) => {
  Object.assign(query, values, { pageNum: 1 });
  handleSearch();
};

/**
 * 关闭弹窗回调
 * @param params
 */
const handleCloseDialog = (params: any) => {
  if (params?.needRefresh) {
    handleSearch();
  }
  closeDialog();
};

const columns = getColumns({
  enableOrEnable,
  openDialog,
  handleUser,
  handleDeleteRole,
});

/**
 * 多删，删除选中的用户
 * @param selectedUsers
 */
async function handleDeleteRoles() {
  const roleIds = checkedRows.value.map((item: any) => item.roleId).join(',');
  const roleName = checkedRows.value.map((item: any) => item.roleName).join(',');

  const dialogRef = dialog.warning({
    title: '删除角色',
    content: `确定要删除选中的 ${roleName} 角色吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      dialogRef.loading = true;
      const res: any = await deleteRole(roleIds);
      if (res.code === 200) {
        message.success('删除成功');
        handleSearch();
        checkedRows.value = []; // reset选中状态
      }
      dialogRef.loading = false;
    },
  });
}

/**
 * 单个删除
 * @param row
 */
async function handleDeleteRole(row: any) {
  try {
    const res: any = await deleteRole(row.roleId);
    if (res.code === 200) {
      message.success('删除成功');
      handleSearch();
    }
  } catch (error) {}
}

function handleChcekedRowKeys(keys: Array<string | number>, rows: object[]) {
  checkedRows.value = rows;
}

/**
 * 停用启用handler
 * @param row
 */
async function enableOrEnable(row: any) {
  row.switchLoading = true;
  let text = row.status === '0' ? '停用' : '启用';
  const res: any = await changeRoleStatus({
    roleId: row.roleId,
    status: row.status === '0' ? '1' : '0',
  });
  if (res.code === 200) {
    message.success(`${text}成功`);
    row.status = row.status === '0' ? '1' : '0';
  } else {
    message.error(`${text}失败`);
  }
  row.switchLoading = false;
}

/**
 * 导出
 */
function handleExport() {
  download('/role/export', { ...query }, `role_${new Date().getTime()}.xlsx`);
}

// 分配用户页
function handleUser(row: any) {
  router.push(`/system/role-auth/user/${row.roleId}`);
}
</script>

<style scoped lang="less"></style>
